/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[欢迎加盟知启蒙，一起邂逅框架梦]
 * 
 * https://www.zhiqim.com/gitcan/zhiqim/zhiqim_account.htm
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.zhiqim.account.action.pay;

import org.zhiqim.account.api.pay.AlipayServer;
import org.zhiqim.account.dbo.user.UserTradeAlipay;
import org.zhiqim.account.paycallback.PayCallback;
import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.httpd.context.core.Action;
import org.zhiqim.kernel.Global;
import org.zhiqim.kernel.logging.Log;
import org.zhiqim.kernel.logging.LogFactory;
import org.zhiqim.orm.ZTable;
import org.zhiqim.orm.dbo.Updater;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayConstants;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.response.AlipayTradeQueryResponse;

/**
 * 获取支付宝GET过来反馈信息
 *
 * @version v1.0.0 @author yangpeng 2018-2-26 新建与整理
 */
public class AlipayReturnAction implements Action, AlipayConstants
{

    private static final Log log = LogFactory.getLog(AlipayReturnAction.class);
    
    public void execute(HttpRequest request) throws Exception
    {
        //第一步，从内容中取出参数
        long tradeId = request.getParameterLong("out_trade_no");
        String tradeNo = request.getParameter("trade_no");
        
        try
        {//第二步，验证参数正确性
            String alipayPublicKey = Global.getService(AlipayServer.class).getAlipayPublicKey();
            boolean signVerified = AlipaySignature.rsaCheckV1(request.getParameterMap(), alipayPublicKey, CHARSET_UTF8, SIGN_TYPE_RSA2);
            if(!signVerified)
            {
                request.returnCloseWindow("签名数据验证失败，请与客服联系");
                return;
            }
        }
        catch(AlipayApiException e)
        {
            request.returnCloseWindow("签名API验证失败，请与客服联系");
            return;
        }
        
        //第三步，从支付宝交易表中取出交易详情
        UserTradeAlipay alipay = Global.get(ZTable.class).item(UserTradeAlipay.class, tradeId);
        if(alipay == null)
        {
            request.returnCloseWindow("该订单不存在，请重新下单");
            return;
        }
        
        //第四步，从支付宝查询交易
        AlipayTradeQueryResponse response = Global.getService(AlipayServer.class).tradeQuery(tradeId, tradeNo);
        if(!response.isSuccess())
        {
            log.error("查询交易失败[%s][%s]", tradeId, response.getSubMsg());
            request.setRedirect("/account/index.htm");
            return;
        }
        
        //第五步，更新返回数据
        Updater updater = new Updater();
        updater.addMust("tradeId", tradeId);
        updater.addField("tradeNo", tradeNo);
        updater.addField("tradeAccount", response.getBuyerLogonId());
        updater.addField("tradeStatus", response.getTradeStatus());
        updater.addField("tradeReturnDesc", request.getParameterMap().toString());
        
        Global.get(ZTable.class).update(UserTradeAlipay.class, updater);
        
        //第六步，回调并返回
        log.info("支付宝返回,用户[" + alipay.getUserId() + "]");
        String callback = alipay.getTradeCallback();

        Object obj = Global.getCreate(Global.getClass(callback));
        PayCallback call = (PayCallback)obj;
        String redirect = call.call(alipay, false);
        
        request.setRedirect(redirect);
    }
}
